package com.yao.zhihudaily.utils;

/**
 * Created by dell on 2015/6/2.
 */

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 用于doGet与response字符串
 */
public final class CommonUtils {
    private CommonUtils(){}

    public static String doGet(String url){
        InputStream is =null;
        String jsonStr = null;
        ByteArrayOutputStream baos=null;
        try {
            URL url1 = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setReadTimeout(4000);

            if (connection.getResponseCode()==200){
                baos = new ByteArrayOutputStream();
                is = connection.getInputStream();
                byte[] arr = new byte[1024];
                int len;
                while ((len=is.read(arr))!= -1){
                    baos.write(arr,0,len);
                }
                jsonStr = new String(baos.toByteArray(),"utf-8");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return jsonStr;
    }

}
